import React, { useState, useEffect } from 'react';
import { useSearchParams } from 'react-router-dom';
import { Search, TrendingUp } from 'lucide-react';
import SearchBox from '../components/SearchBox';
import HotspotCard from '../components/HotspotCard';
import Loading, { HotspotGridSkeleton } from '../components/Loading';
import { searchHotspots } from '../services/api';

const SearchPage = () => {
  const [searchParams, setSearchParams] = useSearchParams();
  const [results, setResults] = useState([]);
  const [loading, setLoading] = useState(false);
  const [searchPerformed, setSearchPerformed] = useState(false);

  const query = searchParams.get('q') || '';
  const platform = searchParams.get('platform') || '';

  const handleSearch = async (searchQuery, filters = {}) => {
    if (!searchQuery.trim()) {
      setResults([]);
      setSearchPerformed(false);
      setSearchParams({});
      return;
    }

    setLoading(true);
    setSearchPerformed(true);

    try {
      // 更新URL参数
      const params = { q: searchQuery };
      if (filters.platforms && filters.platforms.length > 0) {
        params.platforms = filters.platforms.join(',');
      }
      if (filters.timeRange) {
        params.timeRange = filters.timeRange;
      }
      setSearchParams(params);

      // 执行搜索
      const searchResults = await searchHotspots(searchQuery, filters);
      setResults(searchResults);
    } catch (error) {
      console.error('搜索失败:', error);
      setResults([]);
    } finally {
      setLoading(false);
    }
  };

  const handleFilter = (filters) => {
    if (query) {
      handleSearch(query, filters);
    }
  };

  // 页面加载时根据URL参数执行搜索
  useEffect(() => {
    if (query) {
      const filters = {};
      if (searchParams.get('platforms')) {
        filters.platforms = searchParams.get('platforms').split(',');
      }
      if (searchParams.get('timeRange')) {
        filters.timeRange = searchParams.get('timeRange');
      }
      handleSearch(query, filters);
    }
  }, []);

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* 页面标题 */}
        <div className="flex items-center space-x-2 mb-8">
          <Search className="h-8 w-8 text-primary-600" />
          <h1 className="text-3xl font-bold text-gray-900">搜索热点</h1>
        </div>

        {/* 搜索框 */}
        <div className="mb-8">
          <SearchBox
            onSearch={handleSearch}
            onFilter={handleFilter}
            filters={{
              platforms: searchParams.get('platforms')?.split(',') || [],
              timeRange: searchParams.get('timeRange') || '24h'
            }}
          />
        </div>

        {/* 搜索结果 */}
        {loading ? (
          <div>
            <Loading text="搜索中..." />
            <HotspotGridSkeleton count={6} />
          </div>
        ) : searchPerformed ? (
          results.length > 0 ? (
            <div>
              <div className="flex items-center justify-between mb-6">
                <h2 className="text-lg font-semibold text-gray-900">
                  搜索结果
                  <span className="ml-2 text-sm font-normal text-gray-500">
                    找到 {results.length} 个相关话题
                  </span>
                </h2>
                <div className="text-sm text-gray-500">
                  搜索关键词: "{query}"
                </div>
              </div>
              
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {results.map((hotspot, index) => (
                  <HotspotCard
                    key={hotspot.id}
                    hotspot={hotspot}
                    rank={index + 1}
                  />
                ))}
              </div>
            </div>
          ) : (
            <div className="text-center py-12">
              <Search className="h-16 w-16 text-gray-300 mx-auto mb-4" />
              <h3 className="text-lg font-medium text-gray-900 mb-2">
                未找到相关结果
              </h3>
              <p className="text-gray-500 mb-4">
                没有找到包含 "{query}" 的热点话题
              </p>
              <div className="space-y-2 text-sm text-gray-400">
                <p>建议您：</p>
                <ul className="list-disc list-inside space-y-1">
                  <li>检查搜索关键词是否正确</li>
                  <li>尝试使用更简单的关键词</li>
                  <li>调整筛选条件</li>
                </ul>
              </div>
            </div>
          )
        ) : (
          <div className="text-center py-12">
            <TrendingUp className="h-16 w-16 text-gray-300 mx-auto mb-4" />
            <h3 className="text-lg font-medium text-gray-900 mb-2">
              开始搜索热点话题
            </h3>
            <p className="text-gray-500">
              输入关键词搜索各大平台的热门话题
            </p>
            <div className="mt-6 space-y-2 text-sm text-gray-400">
              <p>搜索技巧：</p>
              <ul className="list-disc list-inside space-y-1">
                <li>使用具体的关键词获得更准确的结果</li>
                <li>可以搜索人名、事件、品牌等</li>
                <li>使用筛选器按平台和时间范围过滤</li>
              </ul>
            </div>
          </div>
        )}

        {/* 热门搜索建议（当没有搜索时显示） */}
        {!searchPerformed && !loading && (
          <div className="mt-8 bg-white rounded-lg border border-gray-200 p-6">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">热门搜索</h3>
            <div className="flex flex-wrap gap-2">
              {['科技', '娱乐', '体育', '财经', '时政', '社会'].map((tag) => (
                <button
                  key={tag}
                  onClick={() => handleSearch(tag)}
                  className="px-3 py-2 bg-gray-100 text-gray-600 rounded-lg hover:bg-primary-100 hover:text-primary-700 transition-colors text-sm"
                >
                  {tag}
                </button>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default SearchPage;